package com.soujiayi.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

public class CommonUtils {

	public static ArrayList<HashMap<String, Object>> convertLStrToLMap(
			ArrayList<String> ls) {
		ArrayList<HashMap<String, Object>> lm = new ArrayList<HashMap<String, Object>>();
		if (null != ls) {
			for (int i = 0; i < ls.size(); i++) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put(Constants.SEARCH_LIST_ITEM, ls.get(i));
				lm.add(map);
			}
		}
		return lm;
	}

	public static boolean isNumeric(String str) {
		return isInteger(str) || isDecimal(str);
	}

	public static boolean isDecimal(String str) {
		return Pattern.compile("([1-9]+[0-9]*|0)(\\.[\\d]+)?").matcher(str)
				.matches();
	}

	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	public static boolean isEmpty(String str) {
		return str == null || "".equals(str);
	}

	public static boolean isLetter(String str) {
		Pattern pattern = Pattern.compile("^[a-zA-Z]");
		return pattern.matcher(str).matches();
	}

	public static boolean isCorrectName(String str) {
		Pattern pattern = Pattern.compile("^[a-zA-Z][0-9A-Za-z_]{4,14}");
		return pattern.matcher(str).matches();
	}

	public static boolean isEmailAddress(String email) {
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher matcher = pattern.matcher(email);
		boolean isMatched = matcher.matches();

		return isMatched;
	}

	public static String getUTF8String(String decodeStr) {
		String encodeStr = null;
		try {
			encodeStr = decodeStr == null ? null : new String(
					decodeStr.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
		}
		return encodeStr;
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1) {
					is.close();
					os.close();
					break;
				}
				os.write(bytes, 0, count);

			}
		} catch (Exception ex) {
		}
	}

	public static byte[] readStream(InputStream inStream) throws Exception {

		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);

		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();

	}

	// 递归
	public static long getFileSize(File f)// 取得文件夹大小
	{
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	public static String FormatFileSize(long fileS) {// 转换文件大小
		if (fileS == 0) {
			return "0M";
		}
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	public static byte[] bmpToByteArray(final Bitmap bmp,
			final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	public static boolean isAppInstalled(Context context, String packagename) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
		}
		return (packageInfo == null) ? false : true;
	}
	
	public static void copyAppPicToSDCard(Context context, int resId, String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),resId);

			CompressFormat format = Bitmap.CompressFormat.PNG;
			int quality = 100;
			OutputStream stream = null;
			try {
				stream = new FileOutputStream(file);
			} catch (FileNotFoundException e) {

			}
			bmp.compress(format, quality, stream);
		}
	}
	
	public static Bitmap decodeFile(File f) {
		Bitmap bitmap = null;
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			final int REQUIRED_SIZE = 70;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null,
					o2);
		} catch (FileNotFoundException e) {
		}
		return bitmap;
	}
	
	public static boolean hasSdcard(){
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
                return true;
        }else{
                return false;
        }
}
}
